package com.wzy.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.wzy.server.mapper.EmployeeMapper;
import com.wzy.server.pojo.*;
import com.wzy.server.service.*;
import com.wzy.server.service.impl.EmployeeServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wzy
 * @since 2021-04-30
 */
@RestController
@RequestMapping("/employee/basic")
@Api("员工资料")
@Slf4j
public class EmployeeController {
    @Resource
    private IEmployeeService employeeService;//员工分页
    @Resource
    private INationService nationService;//民族
    @Resource
    private IDepartmentService departmentService;//部门
    @Resource
    private IPositionService positionService;//职位
    @Resource
    private IJoblevelService joblevelService;//职称
    @Resource
    private IPoliticsStatusService politicsStatusService;//政治面貌
    @Resource
    private EmployeeMapper employeeMapper;

    @ApiOperation(value = "获取所有员工（分页）")
    @GetMapping("/")
//                                        默认当前页为1
    public RespPageBean getEmployee(@RequestParam (defaultValue = "1")Integer currentPage,
//                                    每页的大小
                                    @RequestParam(defaultValue = "10")Integer size,
//                                    员个对象              入职时间
                                    Employee employee, LocalDate[] beginDateScope
                                    ){
        return employeeService.getEmployeeByPage(currentPage,size,employee,beginDateScope);
    }

    @ApiOperation(value = "获取所有政治面貌")
    @GetMapping("/politicsstatus")
    public List<PoliticsStatus> getAllPoliticsStatuses(){
        return politicsStatusService.list();
    }
    @ApiOperation(value = "获取所有职称")
    @GetMapping("/joblevels")
    public List<Joblevel> getAllJoblevels(){
        return joblevelService.list();
    }
    @ApiOperation(value = "获取所有民族")
    @GetMapping("/nations")
    public List<Nation> getAllNations(){
        return nationService.list();
    }
    @ApiOperation(value = "获取所有职位")
    @GetMapping("/positions")
    public List<Position> getAllPositions(){
        return positionService.list();
    }
    @ApiOperation(value = "获取所有部门")
    @GetMapping("/deps")
    public List<Department> getAllDepartments(){
        return  departmentService.getAllDepartments();
    }
    @ApiOperation(value = "获取最大工号")
    @GetMapping("/maxWorkID")
    public RespBean maxWorkID(){
        return employeeService.maxWorkID();
    }


    /**
     *  员工添加
     *      1.根据添加的员工身份证号判断员工是否已经存在
     *      2.
     * @param employee
     * @return
     */
    @ApiOperation(value = "添加员工")
    @PostMapping("/")
    public RespBean addEmp(@RequestBody Employee employee) {
        return employeeService.addEmp(employee);
    }

    @ApiOperation(value = "更新员工")
    @PutMapping("/")
    public RespBean updateEmp(@RequestBody Employee employee) {
        if (employeeService.updateById(employee)){//添加员工
            return RespBean.success("更新成功！");
        }
        return RespBean.error("更新失败！");
    }

    @ApiOperation(value = "删除员工")
    @DeleteMapping("/{id}")
    public RespBean deleteEmp(@PathVariable Integer id) {
        if (employeeService.removeById(id)){//添加员工
            return RespBean.success("删除成功！");
        }
        return RespBean.error("删除失败！");
    }



    /**
     * 导出exc
     * @param response
     * @throws IOException
     */
    @ApiOperation("导出表格员工数据")
    @RequestMapping(value = "/export",produces = "application/octet-stream")//流的方式输出，防止中文乱码
    public void exportEmployee(HttpServletResponse response){//以流的形式导出
        List<Employee> list = employeeService.getEmployee(null);//id为空导出所有的
//                                             导出的文件名      工作表sheet      03版本兼容性强，速度快
        ExportParams params=new ExportParams("员工表","员工表", ExcelType.HSSF);
//                             导出工具类                   参数     对象        数据
        Workbook workbook = ExcelExportUtil.exportExcel(params, Employee.class, list);
        ServletOutputStream out =null;
        try {
//            请求的响应头
            response.setHeader("content-type","application/octet-stream");//以流的形式传输
            response.setHeader("content-disposition","attachment;filename="+ URLEncoder.encode("员工表.xls","UTF_8"));//防止中文乱码
            out = response.getOutputStream();//输出流
            workbook.write(out);//写到页面
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (null!=out){
                try {
                    out.close();//关闭流
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }


    @ApiOperation("导入员工数据表格")
    @PostMapping("/import")
    public RespBean importEmployee(MultipartFile file) {
        ImportParams params = new ImportParams();//导入
        params.setTitleRows(1);//去掉标题行（员工表），否则会报错
        List<Nation> nationList = nationService.list();//查询56个民族，只用查询一次
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();//政治面貌
        List<Department> departmentList = departmentService.list();//部门
        List<Joblevel> joblevelList = joblevelService.list();//职称
        List<Position> positionList = positionService.list();//职位
        try {
            //                           导入工具类                    文件流的形式           对象           数据
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, params);
//          遍历员工表获取民族id
            list.forEach(employee -> {
//                                                                                    重写hashcode和equals，有参构造中name为必填信息
//                            通过下标获取nation对象（有id，name）   查询字符串获取下标     创建对象            获取民族name    获取id
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
                employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
            });
            if (employeeService.saveBatch(list)){//插入保存数据
                return RespBean.success("导入成功!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败！");
    }

}
